package club.kingyin.kyblog.core.utils.kyutil;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 创建时间：2020-11-12<br/>
 * 该类封装了对yyyy-MM-dd HH:mm:ss的操作<br/>
 * @author kingyin
 * @version 1.0
 */
public class DateTimeUtil {

    /**
     * 把yyyy-MM-dd HH:mm:ss格式的日期转换成时间戳
     * @param timers 符合格式的日期时间
     * @return 时间戳
     * @throws RuntimeException 日期时间字符串为null
     * @throws RuntimeException 日期转时间戳出错 需要的格式 'yyyy-MM-dd HH:mm:ss'
     */
    public static long datetimeToStamp(String timers) {
        if (timers == null || timers == "")
            throw new RuntimeException("The date and time string is empty");
        Date d;
        long timeStamp = 0;
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            d = sf.parse(timers);// 日期转换为时间戳
        } catch (Exception e) {
            throw new RuntimeException("Date roll time stamp error => required format {yyyy-MM-dd HH:mm:ss}");
        }
        timeStamp = d.getTime();
        return timeStamp;
    }

    public static Date toDate(Date date){
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        ParsePosition pos = new ParsePosition(8);
        Date currentTime_2 = formatter.parse(dateString, pos);
        return currentTime_2;
    }
}
